<template>
    <div class="bg-black pt-4">
        <!-- <el-row> -->
        <!-- <el-col :span="12">
                <aplayer :tricks="musicList"></aplayer>
            </el-col>
            <el-col :span="12" class="text-white"> -->
        <!-- <div>
            <div class="mainPage" ref="playerRef"></div>
        </div> -->

        <el-row>
            <el-col :span="4">
                <div class="radio-inputs" style="position: relative;">
                    <label v-for="(item, index) in playlist" :key="index">
                        <input class="radio-input" type="radio" name="engine" :checked="index === 0"
                            @change="select(item)" />
                        <span class="radio-tile">
                            <span class="radio-icon">
                                <img :src="item.coverImgUrl" style="border-radius: 0.5rem;" />
                            </span>
                            <div class="radio-label w-full">{{ item.name }}[{{ item.trackCount }}]</div>
                        </span>
                    </label>
                </div>
            </el-col>
            <el-col :span="20">

                <div class="main" style="height: 40vh;overflow-y: scroll;">

                    <!-- <div class="currentplaying">
                                <svg viewBox="0 0 640 512" height="1em" xmlns="http://www.w3.org/2000/svg"
                                    fill="#ff8800" class="soundcloud">
                                    <path
                                        d="M111.4 256.3l5.8 65-5.8 68.3c-.3 2.5-2.2 4.4-4.4 4.4s-4.2-1.9-4.2-4.4l-5.6-68.3 5.6-65c0-2.2 1.9-4.2 4.2-4.2 2.2 0 4.1 2 4.4 4.2zm21.4-45.6c-2.8 0-4.7 2.2-5 5l-5 105.6 5 68.3c.3 2.8 2.2 5 5 5 2.5 0 4.7-2.2 4.7-5l5.8-68.3-5.8-105.6c0-2.8-2.2-5-4.7-5zm25.5-24.1c-3.1 0-5.3 2.2-5.6 5.3l-4.4 130 4.4 67.8c.3 3.1 2.5 5.3 5.6 5.3 2.8 0 5.3-2.2 5.3-5.3l5.3-67.8-5.3-130c0-3.1-2.5-5.3-5.3-5.3zM7.2 283.2c-1.4 0-2.2 1.1-2.5 2.5L0 321.3l4.7 35c.3 1.4 1.1 2.5 2.5 2.5s2.2-1.1 2.5-2.5l5.6-35-5.6-35.6c-.3-1.4-1.1-2.5-2.5-2.5zm23.6-21.9c-1.4 0-2.5 1.1-2.5 2.5l-6.4 57.5 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78.6-35 78.6-78.3.1-43.6-35.2-78.9-78.5-78.9zm-296.7-60.3c-4.2 0-7.5 3.3-7.8 7.8l-3.3 136.7 3.3 65.6c.3 4.2 3.6 7.5 7.8 7.5 4.2 0 7.5-3.3 7.5-7.5l3.9-65.6-3.9-136.7c-.3-4.5-3.3-7.8-7.5-7.8zm-53.6-7.8c-3.3 0-6.4 3.1-6.4 6.7l-3.9 145.3 3.9 66.9c.3 3.6 3.1 6.4 6.4 6.4 3.6 0 6.4-2.8 6.7-6.4l4.4-66.9-4.4-145.3c-.3-3.6-3.1-6.7-6.7-6.7zm26.7 3.4c-3.9 0-6.9 3.1-6.9 6.9L227 321.3l3.9 66.4c.3 3.9 3.1 6.9 6.9 6.9s6.9-3.1 6.9-6.9l4.2-66.4-4.2-141.7c0-3.9-3-6.9-6.9-6.9z">
                                    </path>
                                </svg>
                                <p class="heading">Currently Playing</p>
                            </div> -->
                    <!-- <div class="loader">
                                    <div class="song">
                                    <p class="name">Time in a Bottle</p>
                                    <p class="artist">Jim Corce</p>
                                    </div>
                                    <div class="albumcover"></div>
                                    <div class="loading">
                                    <div class="load"></div>
                                    <div class="load"></div>
                                    <div class="load"></div>
                                    <div class="load"></div>
                                    </div>
                                </div> -->
                    <div class="loader" v-for="(item, index) in musicList" :key="index" @click="playsong(item, index)">
                        <div class="song">
                            <p class="name">{{ item.name }}</p>
                            <p class="artist">{{ item.ar.map(item => item.name).join(', ') }}</p>
                        </div>
                        <div class="albumcover">
                            <img :src="item.al.picUrl" />
                        </div>
                        <div class="play" v-if="selectIndex !== index"></div>
                        <div class="loading" v-else>
                            <div class="load"></div>
                            <div class="load"></div>
                            <div class="load"></div>
                            <div class="load"></div>
                        </div>
                    </div>

                </div>
            </el-col>
        </el-row>

        <div class="mx-4 mb-2 h-18" v-if="selectItem">
            <el-row>
                <el-col :span="4">
                    <img :src="selectItem.al.picUrl" class="w-16 rounded-full m-1 spinning" />
                </el-col>
                <el-col :span="20">
                    <div class="mt-4 text-white">{{ selectItem.name }} <span class="ml-4">{{ txts }}</span></div>
                    <div>
                        <el-progress :percentage="percentage" striped color="#dd0b0b">
                            <el-button text style="color:#fff">{{ timer }}</el-button>
                        </el-progress>
                    </div>
                </el-col>
            </el-row>
           

        </div>
        <div class="h-2"></div>
        <!-- </el-col>
        </el-row> -->

    </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted } from 'vue'
import { useRoute } from 'vue-router';
import ax from '@/helper/axios.js'
import moment from 'moment';

moment.locale('zh-cn');
 import Lyric from 'lyric-parser'
const music = ref([])
const playlist = ref([])
const selectIndex = ref(null);
const selectItem = ref(null);
let timer = ref('')
let percentage = ref(0)
//判断 localStorage中是否有存储 
const res = JSON.parse(window.localStorage.getItem('musicuser') || '{}')
console.log('res:', res)
//如果没有  执行 musiclogin() 
//判断 res 是否为 {}

// if (JSON.stringify(res) === '{}') {
//     musiclogin();
// } else {
ax.post('/wym/user/playlist?uid=72541684').then(res => {

    playlist.value = res.playlist
    console.log(' playlist.value :', playlist.value)
    select(playlist.value[0])
});
//}
function hanlder({lineNum, txt}){
   // this hanlder called when lineNum change
 }
function musiclogin() {
    ax.get('/wym/login/cellphone?phone=18624024313&password=Zt04985807').then(res => {
        console.log(res);
        //把 res 存入 localStorage 缓存中
        localStorage.setItem('musicuser', JSON.stringify(res));
    }).catch((err) => {
        console.log(err);

    });

}
const musicList = ref([])
async function select(item) {
    musicList.value = [];
    let m = [];
    await ax.get('/wym/playlist/detail?id=' + item.id).then(res => {
        console.log('select', res);
        musicList.value = res.playlist.tracks;

        // res.playlist.tracks.forEach(element => {
        //     console.log(element)

        //     // ax.get('/wym/song/url/v1?id=' + element.id + '&level=exhigh').then(res => {
        //     //     var obj = {
        //     //         name: element.ar[0].name,
        //     //         artist: element.name,
        //     //         cover: element.al.picUrl,
        //     //         source: res.data[0].url,
        //     //         url: element.al.picUrl,
        //     //         favorited: false
        //     //     }

        //     //     m.push(obj)
        //     // })
        //     // musicList.value=m
        //     // console.log('musicList.value', musicList.value)
        // });
    }).catch((err) => {
        console.log(err);

    });
}
let audio = null;

const txts = ref('')
async function playsong(item, index) {
   
    music.value = [];
    ax.get('/wym/song/url/v1?id=' + item.id + '&level=exhigh').then(res => {
        txts.value = '';
        console.log(res, res.data[0].url)
        ax.get('/wym/lyric/new?id=' + item.id).then(res2 => {
            console.log('res2', res2)
            const regNewLine = /\n/
            const lineArr = res2.lrc.lyric.split(regNewLine)
            console.log('lineArr:', lineArr)
            let lyric = new Lyric(res2.lrc.lyric, function({lineNum, txt}){
            	console.log('txt:', txt)
                txts.value = txt
            	console.log('lineNum:', lineNum)
                
            })
            	console.log('lyric:', lyric)
            lyric.play();
        });

        //         music.value.push({
        //             id: 0,
        //             name: item.name,
        //             author: item.ar.map(item => item.name).join(', '),
        //             url: res.data[0].url,

        //         });

        //         if (audioRef.value && audioRef.value.play) {
        //     audioRef.value.play();
        //   }


        if (audio && selectItem.value.id === item.id) {
        console.log('item.id:', item.id)
        console.log('electItem.value.id:', selectItem.value.id)
           
                console.log('audio:', audio)
                // 如果有，暂停当前音乐
                audio.pause();
                audio = null;
                percentage.value = 0
                timer.value = '';
                selectIndex.value = null;
                selectItem.value = null;
           
            // 可选：停止音乐并释放资源
            // currentAudio.currentTime = 0;
        }
        else {
            selectIndex.value = index
            selectItem.value = item;
            if (audio){
             audio.pause();
             audio = null;
            }
            audio = new Audio(res.data[0].url)
            audio.play();
            let duration = moment(res.data[0].time);
            console.log('res.data[0].time:', res.data[0].time)
            console.log('duration:', duration)
            let formattedTimeNoZero = duration.format('mm:ss', { trim: false });
            console.log('formattedTimeNoZero:', formattedTimeNoZero)
            // 监听音频播放的时间变化
            audio.addEventListener('timeupdate', function () {
                console.log('当前播放时间:', audio.currentTime);
                let duration = moment(audio.currentTime * 1000);
                console.log('duration:', duration)
                let formattedTimeNoZero2 = duration.format('mm:ss', { trim: false });
                timer.value = formattedTimeNoZero2 + '/' + formattedTimeNoZero
                console.log(' timer.value:', timer.value)

                // 将时间转换为 moment 对象
                const momentTime1 = moment.duration(formattedTimeNoZero2);
                const momentTime2 = moment.duration(formattedTimeNoZero);

                // 计算毫秒数
                const milliseconds1 = momentTime1.asMilliseconds();
                const milliseconds2 = momentTime2.asMilliseconds();

                // 计算第一个时间长度是第二个时间长度的百分比
                const p = (milliseconds1 / milliseconds2) * 100;
                percentage.value = p
                console.log('percentage.value:', percentage.value)
            });

            // 检查音频是否已经播放完毕
            audio.addEventListener('ended', function () {
                console.log('音频播放结束');
                audio = null;
                percentage.value = 0
                timer.value = '';

                if (index == musicList.value.length) {
                    selectIndex.value = 0
                    selectItem.value = musicList.value[0];
                    playsong(musicList.value[0], 0)
                }
                else {
                    selectIndex.value = index + 1
                    selectItem.value = musicList.value[index + 1];
                    playsong(musicList.value[index + 1], index + 1)
                }
            });
        }

    })

}
onMounted(() => { });
</script>
<style scoped lang="less">
@keyframes spin {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}

img.spinning {
    animation: spin 5s linear infinite;
    /* 5秒内无限循环旋转 */
}

/* 样式定义 */
.radio-inputs {
    position: fixed;
    top: 50px;
    left: 1%;


    align-items: center;
    justify-content: center;
    max-width: 50px;
    margin: 0 auto;
    user-select: none;
    z-index: 999999
}

.radio-inputs2 {
    position: fixed;
    bottom: 50px;
    left: 1%;


    align-items: center;
    justify-content: center;
    max-width: 50px;
    margin: 0 auto;
    user-select: none;
    z-index: 999999
}

.radio-inputs>* {
    margin: 6px;
}

.radio-input:checked+.radio-tile {
    color: #dd0b0b;
    border-color: #dd0b0b;
    box-shadow: 0 5px 10px rgb(0 0 0 / 10%);
}

.radio-input:checked+.radio-tile::before {
    background-color: #dd0b0b;
    border-color: #dd0b0b;
    opacity: 1;
    transform: scale(1);
}

.radio-input:checked+.radio-tile .radio-icon svg {
    fill: #dd0b0b;
}

.radio-input:checked+.radio-tile .radio-label {
    color: #fff;
    background-color: #dd0b0b;
}

.radio-input:focus+.radio-tile {
    border-color: #dd0b0b;
    box-shadow: 0 5px 10px rgb(0 0 0 / 10%), 0 0 0 4px #b5c9fc;
}

.radio-input:focus+.radio-tile::before {
    opacity: 1;
    transform: scale(1);
}

.radio-input:focus+.radio-icon svg {
    width: 2rem;
    height: 2rem;
    fill: #dd0b0b;
}

.radio-tile {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 80px;
    min-height: 80px;
    font-weight: 800;
    cursor: pointer;
    background-color: transparent;
    border: 2px solid #fff;
    border-radius: 0.5rem;
    box-shadow: 0 5px 10px rgb(0 0 0 / 10%);
    transition: 0.15s ease;
}

.radio-tile::before {
    position: absolute;
    top: 0.25rem;
    left: 0.25rem;
    display: block;
    width: 0.75rem;
    height: 0.75rem;
    content: '';
    background-color: #dd0b0b;
    border: 2px solid #fff;
    border-radius: 50%;
    opacity: 0;
    transition: 0.25s ease;
    transform: scale(0);
}

.radio-tile:hover {
    border-color: #dd0b0b;
}

.radio-tile:hover::before {
    opacity: 1;
    transform: scale(1);
}

.radio-icon svg {
    width: 2rem;
    height: 2rem;
    fill: #fff;
}

.radio-label {
    margin-top: 6px;
    font-size: 13px;
    color: #000;
    text-align: center;
    background-color: #fff;
    transition: 0.375s ease;
}

.radio-input {
    position: absolute;
    width: 1px;
    height: 1px;
    overflow: hidden;
    clip: rect(0 0 0 0);
    clip-path: inset(100%);
    white-space: nowrap;
}

.radio2-tile {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 80px;
    min-height: 80px;
    font-weight: 800;
    cursor: pointer;
    background-color: transparent;
    border: 2px solid #3883e6;
    border-radius: 0.5rem;
    box-shadow: 0 5px 10px rgb(0 0 0 / 10%);
    transition: 0.15s ease;
}

.radio2-tile::before {
    position: absolute;
    top: 0.25rem;
    left: 0.25rem;
    display: block;
    width: 0.75rem;
    height: 0.75rem;
    content: '';
    background-color: #3883e6;
    border: 2px solid #fff;
    border-radius: 50%;
    opacity: 0;
    transition: 0.25s ease;
    transform: scale(0);
}

.radio2-tile:hover {
    border-color: #3883e6;
}

.radio2-tile:hover::before {
    opacity: 1;
    transform: scale(1);
}

.radio2-icon svg {
    width: 2rem;
    height: 2rem;
    fill: #fff;
}

.radio2-label {
    margin-top: 6px;
    font-size: 13px;
    color: #fff;
    text-align: center;
    background-color: #3883e6;
    transition: 0.375s ease;
}

.radio2-input {
    position: absolute;
    width: 1px;
    height: 1px;
    overflow: hidden;
    clip: rect(0 0 0 0);
    clip-path: inset(100%);
    white-space: nowrap;
}

.radio3-tile {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 80px;
    min-height: 80px;
    font-weight: 800;
    cursor: pointer;
    background-color: transparent;
    border: 2px solid #059469;
    border-radius: 0.5rem;
    box-shadow: 0 5px 10px rgb(0 0 0 / 10%);
    transition: 0.15s ease;
}

.radio3-tile::before {
    position: absolute;
    top: 0.25rem;
    left: 0.25rem;
    display: block;
    width: 0.75rem;
    height: 0.75rem;
    content: '';
    background-color: #059469;
    border: 2px solid #fff;
    border-radius: 50%;
    opacity: 0;
    transition: 0.25s ease;
    transform: scale(0);
}

.radio3tile:hover {
    border-color: #059469;
}

.radio3-tile:hover::before {
    opacity: 1;
    transform: scale(1);
}

.radio3-icon svg {
    width: 2rem;
    height: 2rem;
    fill: #fff;
}

.radio3-label {
    margin-top: 6px;
    font-size: 13px;
    color: #fff;
    text-align: center;
    background-color: #059469;
    transition: 0.375s ease;
}

.radio3-input {
    position: absolute;
    width: 1px;
    height: 1px;
    overflow: hidden;
    clip: rect(0 0 0 0);
    clip-path: inset(100%);
    white-space: nowrap;
}


/* From Uiverse.io by ahmed150up2 */
.main {
    background-color: white;
    padding: 1em;
    padding-bottom: 1.1em;
    border-radius: 15px;
    margin: 1em;
}

.loader {
    display: flex;
    flex-direction: row;
    height: 4em;
    padding-left: 1em;
    padding-right: 1em;
    transform: rotate(180deg);
    justify-content: right;
    border-radius: 10px;
    transition: .4s ease-in-out;
}

.loader:hover {
    cursor: pointer;
    background-color: lightgray;
}

.currentplaying {
    display: flex;
    margin: 1em;
}

.soundcloud {
    width: 50px;
    height: 50px;
    margin-right: 0.6em;
}

.heading {
    color: black;
    font-size: 1.1em;
    font-weight: bold;
    align-self: center;
}

.loading {
    display: flex;
    margin-top: 1em;
    margin-left: 0.3em;
}

.load {
    width: 2px;
    height: 33px;
    background-color: #ff8800;
    animation: 1s move6 infinite;
    border-radius: 5px;
    margin: 0.1em;
}

.load:nth-child(1) {
    animation-delay: 0.2s;
}

.load:nth-child(2) {
    animation-delay: 0.4s;
}

.load:nth-child(3) {
    animation-delay: 0.6s;
}

.play {
    position: relative;
    left: 0.35em;
    height: 1.6em;
    width: 1.6em;
    clip-path: polygon(50% 50%, 100% 50%, 75% 6.6%);
    background-color: black;
    transform: rotate(-90deg);
    align-self: center;
    margin-top: 0.7em;
    justify-self: center;
}

.albumcover {
    position: relative;
    margin-right: 1em;
    height: 40px;
    width: 40px;
    background-color: rgb(233, 232, 232);
    align-self: center;
    border-radius: 5px;
}

.song {
    position: relative;
    transform: rotate(180deg);
    margin-right: 1em;
    color: black;
    align-self: center;
}

.artist {
    font-size: 0.6em;
}

@keyframes move6 {
    0% {
        height: 0.2em;
    }

    25% {
        height: 0.7em;
    }

    50% {
        height: 1.5em;
    }

    100% {
        height: 0.2em;
    }
}
</style>